import {Component, Input, OnInit, TemplateRef} from "@angular/core";
import {NzDrawerRef, NzDrawerService, NzMessageService} from "ng-zorro-antd";
import {I18NService} from "@core/i18n/i18n.service";
import {FormBuilder, FormGroup} from "@angular/forms";
import {PopupService} from "@shared/popup/popup.service";
import {Router} from "@angular/router";
import {Observable} from "rxjs";
import {HttpClient} from "@angular/common/http";
import { saveAs } from 'file-saver';
import {ViewChild} from "@angular/core";
import {QuestionService} from "../../question/service/question.service";
import {Question} from "../../question/model/question";
import {QuestionModifyComponent} from "../../question/modify/question-modify.component";
import {NzDrawerCustomComponent} from "./nz-drawer-custom-component";

@Component({
  styles: [],
  templateUrl: './paper-handAdd.html'
})
export class PaperHandAddComponent implements OnInit {
  @ViewChild('drawerTemplate') drawerTemplate: TemplateRef<{
    $implicit: { value: string };
    drawerRef: NzDrawerRef<any>;
  }>;
  constructor(
    private message: NzMessageService,
    private i18nService: I18NService,
    private questionService: QuestionService,
    private fb: FormBuilder,
    private popupService: PopupService,
    private router:Router,
    private http: HttpClient,
    private drawerService: NzDrawerService
  ) {
    this.validateForm = this.fb.group({
      questionType:'所有题型',
      content:null
    });
  }
  idArr=[];
  validateForm: FormGroup;
  questionByTypeList=['所有题型','单选题','多选题','判断题','填空题','解答题','编程题'];
  ngOnInit(): void {
    this.getAllQuestionByPage(true);
  }
  goInsert(){
    this.router.navigateByUrl('/main/question/questionInsert');
  }

  submit(){}


  getQuestionByType(e):void{
    this.getAllQuestionByPage(true);
  }

  showModify(item?: any): void {

    if (item !== undefined) {
      let params = {
        id: item.id
      };
      let title = '试题修改';
      this.popupService.create({
        title: title,
        content: QuestionModifyComponent,
        componentParams: params,
        width: 1000,
        onSubmit: (res) => {
          this.getAllQuestionByPage(true);
        },
        onCancel: (res) => { }
      }).afterClose.subscribe(res => { });
    }else{
      this.router.navigateByUrl('/main/question/questionModify');
    }

  }

  page = {
    pageNo: 1,
    pageSize: 10,
    total: 1
  };

  _loading = false;

  listOfData: Question[] = [];
  bordered = true;
  pagination = true;
  header = true;
  size = 'default';
  expandable = true;
  checkbox = true;
  allChecked = false;
  indeterminate = false;
  displayData: any[] = [];
  simple = false;
  noResult = false;
  position = 'bottom';

  currentPageDataChange(
    $event: Array<{
      name: string;
      age: number;
      address: string;
      checked: boolean;
      expand: boolean;
      description: string;
    }>
  ): void {
    this.displayData = $event;
    this.refreshStatus(0,0);
  }

  refreshStatus(e,id:number): void {
    if(e!==0){
      if(e===true){
        if(this.idArr.indexOf(id)==-1){
          this.idArr.push(id);
        }
      }else{
        if(this.idArr!==undefined&&this.idArr.length>0){
          if(this.idArr.indexOf(id)!==-1){
            let tailId=this.idArr.pop();
            if(tailId!==id){
              this.idArr[this.idArr.indexOf(id)]=tailId;
            }
          }
        }
    }
    }
    const validData = this.displayData.filter(value => !value.disabled);
    const allChecked = validData.length > 0 && validData.every(value => value.checked === true);
    const allUnChecked = validData.every(value => !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  checkAll(value: boolean,listOfData: Question[]): void {

    this.displayData.forEach(data => {
      if (!data.disabled) {
        data.checked = value;
      }
    });
    if(value===true){
      listOfData.forEach(res=>{
       if(this.idArr.indexOf(res.id)===-1){
         this.idArr.push(res.id);
       }
      });
    }else {
      listOfData.forEach(res=>{
        if(this.idArr.indexOf(res.id)!==-1){
          let tailId=this.idArr.pop();
          if(res.id!==tailId){
            this.idArr[this.idArr.indexOf(res.id)]=tailId;
          }
        }

      });

    }
    this.refreshStatus(0,0);
  }

  noResultChange(status: boolean): void {
    this.listOfData = [];
    if (!status) {
      this.ngOnInit();
    }
  }


  private getDisposition(data: string) {
    const arr: any = (data || '')
      .split(';')
      .filter(i => i.includes('='))
      .map(v => {
        const strArr = v.split('=');
        const utfId = `UTF-8''`;
        let value = strArr[1];
        if (value.startsWith(utfId)) {
          value = value.substr(utfId.length);
        }
        return { [strArr[0].trim()]: value };
      });
    return arr.reduce((o, item: any) => item, {});
  }


  getAllQuestionByPage(reset = false):  void {
    if (reset) {
      this.page.pageNo = 1;
    }
    if (!this._loading) {
      this._loading = true;
      this.questionService.getAllQuestionByPage(this.validateForm.value.content,this.page.pageNo, this.page.pageSize, this.validateForm.value.questionType)
        .subscribe(res => {
          this.listOfData = res.records;
          this.listOfData.forEach(date=>{
            if(this.idArr.indexOf(date.id)!==-1){
              date.checked=true;
            }
          });
          this.page.total = res.total;
          this._loading = false;
        }, err => {
          this._loading = false;
          this.listOfData = [];
        });
    }
  }

  delete(id: number) {
    this.questionService.deltetQuestion(id)
      .subscribe(res => {
        if (res) {
          this.message.success(this.i18nService.translate('modify.return.delete_success'));
          this.getAllQuestionByPage();
        } else {
          this.message.error(this.i18nService.translate('modify.return.delete_error'));
        }
      });
  }

  search():void{
    this.getAllQuestionByPage(true);
  }

  exportQuestionByIds(idStr:string):void {
    this.http.get( '/get/web/download/questionModule/QuestionService/exportQuestionByIds', {responseType:'blob',observe:'response',params:{idStr}})
      .subscribe(res => {
        if (res.status !== 200 || res.body.size <= 0) {
          this.message.error(this.i18nService.translate('导出失败'));
          return;
        }
        const name=res.headers.get('Content-disposition');
        const disposition: any = this.getDisposition(name);
        const fileName =
          disposition[`filename*`] ||
          disposition[`filename`] ||
          res.headers.get('filename') ||
          res.headers.get('x-filename');
        saveAs(res.body, decodeURI(fileName));
        this.message.success(this.i18nService.translate('导出成功'));
      }, err => {
        this.message.error(this.i18nService.translate('导出失败'));
      });
  }

  openComponent(): void {
    // let idArr=[];
    // this.displayData.forEach(data => {
    //   if (data.checked===true) {
    //     idArr.push(data.id);
    //   }
    // });

    let idStr=this.idArr.join(',');
    const drawerRef = this.drawerService.create<NzDrawerCustomComponent, { idStr: string }, string>({
      nzTitle: 'Component',
      nzContent: NzDrawerCustomComponent,
      nzWidth:1200,
      nzContentParams: {
        idStr: idStr
      }
    });
    drawerRef.afterOpen.subscribe(() => {
      console.log('Drawer(Component) open');
    });

    drawerRef.afterClose.subscribe(data => {
      console.log(data);

    });
  }


}

